package crons

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/service"
)

func init() {
	cron.Register(AuctionClosed)
}

var AuctionClosed = &cAuctionClosed{name: "auction_closed"}

type cAuctionClosed struct {
	name string
}

func (c *cAuctionClosed) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cAuctionClosed) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	// 业务逻辑
	var (
		mapperList []entity.AuctionProductMapper
	)
	// 查询已结束的竞拍活动
	if err = service.SysAuctionProductMapper().Model(ctx).
		Where(dao.AuctionProductMapper.Columns().Status, consts.AuctionStatusEnd).
		Scan(&mapperList); err != nil {
		parser.Logger.Warning(ctx, "cron AuctionClosed Execute err: ", err)
		return
	}
	for _, mapper := range mapperList {
		var auction entity.Auction
		if err = service.SysAuction().Model(ctx).WherePri(mapper.AuctionId).Scan(&auction); err != nil {
			parser.Logger.Warning(ctx, "cron AuctionClosed Execute err: ", err)
			continue
		}
		if auction.EndDate.Before(gtime.Now()) {
			if _, err = service.SysAuctionProductMapper().Model(ctx).WherePri(mapper.Id).Data(g.Map{
				dao.AuctionProductMapper.Columns().Status: consts.AuctionStatusClosed,
			}).Update(); err != nil {
				parser.Logger.Warning(ctx, "cron AuctionClosed Execute err: ", err)
				continue
			}
		}
	}
	return
}
